<template>
  <template v-if="getShow">
    <LoginFormTitle class="enter-x" />
    <div class="enter-x min-w-64 min-h-64">
      <Tabs v-model:activeKey="activeGrantType" :tabBarGutter="15">
        <TabPane 
          v-for="item in qrCodeLdpConnectList"
          :key="item.grantType" 
          :tab="item.displayName" forceRender 
        > 
          <div class="enter-x flex justify-center xl:justify-start">
            <Image
              :width="300" :preview="false"
              :src="compState.qrCodeUrl"
            />
            <div :class="`${prefixCls}-expired`" v-if="compState.isExpired" @click="loadQrCode">
              <span>{{ compState.errMsg }}</span>
            </div>
          </div>
        </TabPane>
      </Tabs>
      <Divider class="enter-x">{{ scanContent }}</Divider> 
      <Button size="large" block class="mt-4 enter-x" @click="handleBackLogin">
        {{ t('sys.login.backSignIn') }}
      </Button>
    </div>
    <ThirdBindUserModal @register="registerModal" />
    <LoginSelect ref="loginSelectRef" />
  </template>
</template>
<script lang="ts" setup>
  import { computed, onMounted, unref, ref, watch } from 'vue';
  import { getPlatformConfig } from '/@/utils/cache/module'
  import { useDesign } from '/@/hooks/web/useDesign';
  import LoginFormTitle from './LoginFormTitle.vue';
  import { Button, Divider, TabPane, Tabs, Image } from 'ant-design-vue';
  import { useUserStore } from '/@/store/modules/user';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useLoginState, LoginStateEnum, GrantTypeEnum, qrCodeGrantTypes} from './useLogin';
  import { getLoginQrcode, getQrcodeToken } from '/@/api/auth';
  import LoginSelect from './LoginSelect.vue';
  import ThirdBindUserModal from './ThirdBindUserModal.vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useModal } from '/@/components/Modal';

  const { createMessage, notification } = useMessage();
  const compState = ref<any>({
    qrCodeUrl: undefined,
    qrcodeId: undefined,
    isExpired: false,
    errMsg: '二维码已过期'
  });
  let timer: IntervalHandle;
  const { t } = useI18n();
  const authToken = ref<any>({})
  const loginSelectRef = ref<any>()
  const { prefixCls } = useDesign('qr-code-login');
  const userStore = useUserStore();
  const { handleBackLogin, getLoginState } = useLoginState();
  const state = ref('0');
  const ldpConnectList : any[] = getPlatformConfig()?.ldpConnectList || []
  // 二维码登录方式的身份源连接
  const qrCodeLdpConnectList = ldpConnectList.filter(e=> qrCodeGrantTypes.includes(e.grantType))
  const [registerModal, { openModal }] = useModal();
  const activeGrantType = ref(qrCodeLdpConnectList.length > 0 ? qrCodeLdpConnectList[0].grantType : '')
  const getShow = computed(() => unref(getLoginState) === LoginStateEnum.QR_CODE)
  const scanContent = computed(() => {
    return unref(state) === '0' ? t('sys.login.scanSign') : t('sys.login.scanSuccess');
  });
  //加载二维码信息
  function loadQrCode() {
    state.value = '0';
    getLoginQrcode({ grantType: unref(activeGrantType)}).then((res) => {
      compState.value = {...res, isExpired: false, errMsg: '二维码已过期'};
      if (res.qrcodeId) {
        openTimer(res.qrcodeId);
      }
    }).catch(e => {
      console.log(e);
      handleBackLogin()
    })
  }
  
  //监控扫码状态
  async function watchQrcodeToken(qrcodeId) {
    getQrcodeToken({ qrcodeId: qrcodeId }).then( async (res) => {
      let data = res.data;
      let code = res.code;
      if (code == 3015) {
        compState.value.isExpired = true
        clearInterval(timer);
      }  else if (code !== 1) {
        compState.value.isExpired = true
        compState.value.errMsg = res.message
        clearInterval(timer);
      }
      
      // 扫码成功
      if (res.success && data.isScan) {
        state.value = '2';
        authToken.value = data.authToken
        clearInterval(timer);

        if (data.isBind) {
          await userStore.thirdLogin(data.authToken)
          loginSelectRef.value.show()
          return
        }
        
        // 打开用户绑定模型
        openModal(true, data)
      }
    }).catch(e => {
      compState.value.isExpired = true
      compState.value.errMsg = e.message
      clearInterval(timer);
    })
  }

  /** 开启定时器 */
  function openTimer(qrcodeId) {
    watchQrcodeToken(qrcodeId);
    closeTimer();
    timer = setInterval(() => {
      watchQrcodeToken(qrcodeId);
    }, 1500);
  }

  /** 关闭定时器 */
  function closeTimer() {
    if (timer) clearInterval(timer);
  }

  watch(getShow, (v) => {
    if (v) {
      loadQrCode();
    } else {
      closeTimer();
    }
  });
</script>

<style lang="less">
  @prefix-cls: ~'@{namespace}-qr-code-login';

  .@{prefix-cls} {
    &-expired {
      cursor: pointer;
      // background-color: rgba(0,0,0,.75);
      background:rgba(255,255,255,0.95);
      z-index: 1000;
      content: "";
      width: 300px;
      height: 300px;
      position: absolute;
      left: 50%;
      top: 50%;

      transform: translate(-50%,-50%);

      span {
        position: absolute;
        left: 50%;
        top: 50%;
        color: #000000;
        white-space: nowrap;
        transform: translate(-50%,-50%);
      }
    }
    
  }
</style>
